export class WebSocketHeartbeat {
  constructor(url, fn, pingInterval = 20000, pongInterval = 10000) {
    this.url = url;
    this.pingInterval = pingInterval;
    this.pongInterval = pongInterval;
    this.reconnectTimeout = null;
    this.heartbeatInterval = null;
    this.pongInterval = null;
    this.ws = null;
    this.fn = fn;
    this.isConnected = false;
    this.connect();
  }

  connect() {
    this.ws = new WebSocket(this.url);
    this.initEventHandlers();
  }

  initEventHandlers() {
    this.ws.onopen = () => {
      this.isConnected = true;
      console.log("onopen");
      this.startHeartbeat();
    };

    this.ws.onerror = () => {
      console.log("onerror");
      this.isConnected = false;
      this.reconnect();
    };

    this.ws.onclose = () => {
      this.isConnected = false;
      this.reconnect();
    };

    this.ws.onmessage = (ev) => {
      // 处理服务器发送的消息
      if (typeof this.fn === "function") {
        this.fn(ev.data);
      }
    };
  }

  startHeartbeat() {
    this.heartbeatInterval = setInterval(() => {
      if (this.ws.readyState === WebSocket.OPEN) {
        this.ws.send("ping");
      }
    }, this.pingInterval);

    this.pongInterval = setInterval(() => {
      if (this.isConnected === false) {
        this.reconnect();
      }
    }, this.pongInterval);
  }

  reconnect() {
    if (this.reconnectTimeout) {
      clearTimeout(this.reconnectTimeout);
      this.reconnectTimeout = null;
    }
    this.reconnectTimeout = setTimeout(() => {
      this.connect();
    }, 5000);
  }

  close() {
    clearInterval(this.heartbeatInterval);
    this.heartbeatInterval = null;
    clearInterval(this.pongInterval);
    this.pongInterval = null;
    clearTimeout(this.reconnectTimeout);
    this.reconnectTimeout = null;
    this.ws.close();
  }
}
export class SpeakerMessage {
  constructor() {
    this.speech = null;
    this.speechSynth = null;
    this.init();
  }
  speak(message) {
    this.speech.text = message; // 播报消息
    this.speech.lang = "zh-CN"; // 设置语言
    this.speech.pitch = 2;
    this.speech.volume = 1;
    this.speech.rate = 1;
    console.log(this.speech, "213234");
    this.speechSynth
      ? this.speechSynth.speak(this.speech)
      : window.speechSynthesis.speak(this.speech); // 播报消息
  }
  cancelSpeak() {
    this.speechSynth.cancel();
  }
  init() {
    if (!("speechSynthesis" in window)) {
      alert("您的浏览器不支持语音合成播报。");
    }
    this.speech = new SpeechSynthesisUtterance();
    this.speechSynth = window.speechSynthesis;
  }
}
